package cn.bby.tools.actions;

import cn.bby.tools.dialog.GenCurlDialog;
import cn.bby.tools.dialog.common.BaseResultDisplayDialog;
import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;

/**
 * 根据当前打开的Spring Controller方法生成curl命令
 *
 * @author ben
 * @version 1.0
 */
public class GenCurlAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        PsiMethod method = getSelectedMethod(e);
        if (method == null) {
            return;
        }
        BaseResultDisplayDialog dialog = new GenCurlDialog(e.getProject(), "生成的Curl命令", method);
        // 显示结果对话框
        dialog.show();
    }

    private PsiMethod getSelectedMethod(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            return null;
        }

        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor == null) {
            return null;
        }

        PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
        if (!(psiFile instanceof PsiJavaFile)) {
            return null;
        }

        // 获取当前光标位置的元素
        int offset = editor.getCaretModel().getOffset();
        PsiElement element = psiFile.findElementAt(offset);

        // 查找包含的Controller方法
        return PsiTreeUtil.getParentOfType(element, PsiMethod.class);
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        if (e.getProject() == null
                || e.getData(CommonDataKeys.EDITOR) == null
                || !(e.getData(CommonDataKeys.PSI_FILE) instanceof PsiJavaFile)) {
            e.getPresentation().setVisible(false);
            return;
        }
    }
}